import React from 'react';
import {Menu,Button,Dropdown,Input,Row,Col,DatePicker,Table,message } from 'antd';
import { DownOutlined,UserOutlined,PlusOutlined,MinusOutlined  } from '@ant-design/icons';
import Moment from 'moment'
import './css/AddToDepot.css'
import axios from "axios";
import {getSessionStoreage} from "../../util/storeage";
import {withRouter} from 'react-router-dom'

const { TextArea } = Input
const dateFormat = 'YYYY-MM-DD hh:mm:ss'
var today = Moment().subtract('1','day').format(dateFormat)

function handleMenuClick(e) {
    console.log('click', e);
}

const pageNation = {
    hideOnSinglePage:true,
    pageSize:10,
    size:'small',
    total:7,
    backgroundColor:'#4BD0B6',
}
class AddPurchaseOrder extends React.Component {
    constructor(){
        super()
        this.state = {
            data:[
                {key:1}
            ],
            myDepot:[],
            depotSelectValue:'',
            myDate:'',
            goodsData:[],
            selectName:'',
            myOrderId:'',
            myType:'',
            userName:'',
            creator:'',
            note:'',
            userId:''
        }
    }
    selectCompany(obj){
        console.log(obj.key)
        let company = ['可口可乐','农夫山泉','长虹电器']
        this.setState({
            depotSelectValue:company[obj.key-1]
        })
    }
    menu = (
        <Menu onClick={this.selectCompany.bind(this)}>
            <Menu.Item key="1" icon={<UserOutlined />}>
                可口可乐
            </Menu.Item>
            <Menu.Item key="2" icon={<UserOutlined />}>
                农夫山泉
            </Menu.Item>
            <Menu.Item key="3" icon={<UserOutlined />}>
                长虹电器
            </Menu.Item>
        </Menu>
    );

    onOk(value) {
        this.setState({
            myDate: value._i
        })
    }
    addRow(){
        let num = this.state.data.length
        let id = this.state.data[num-1].key+1
        let data = {key:id}
        let newData = this.state.data
        newData.push(data)
        this.setState({
            data:[...newData]
        })
    }
    removeRow(obj){
        let data = this.state.data
        data.map((item,i)=>{
            if(item.key===obj.key&&data.length!==1){
                data.splice(i,1)
                data.map(j=>{
                    if(j.key>i){
                        j.key-=1
                    }
                })
            }
            return item
        })
        this.setState({
            data:[...data]
        })
    }
    goodsSelected(item){
        this.setState({
            selectName:item.goodsName
        })
        let oldData = this.state.data
        let i = oldData.length-1
        oldData[i].goodsType = item.goodsSpecifications
        oldData[i].goodsUnit = item.goodsUnit.goodsUnitName
        oldData[i].goodsName = item.goodsName
        oldData[i].goodsId = item.goodsId
        this.setState({
            data:oldData
        })
    }
    changeNum=(e,key)=>{
        let newData = this.state.data
        newData.map(item=>{
            if(item.key===key){
                item.stockInOut = parseInt(e.target.value)
                if(!item.purchaseCost){
                    item.purchaseCost = 0
                }
                item.price = item.stockInOut*item.purchaseCost
                if(!item.price){
                    item.price = ''
                }
            }
        })
        this.setState({
            data:newData
        })
    }
    changePrice=(e,key)=>{
        let newData = this.state.data
        newData.map(item=>{
            if(item.key===key){
                item.purchaseCost = parseInt(e.target.value)
                if(!item.stockInOut){
                    item.stockInOut = 0
                }
                item.price = item.stockInOut*item.purchaseCost
                if(!item.price){
                    item.price = ''
                }
            }
        })
        this.setState({
            data:newData
        })
    }
    changeNote=(e,key)=>{
        let newData = this.state.data
        newData.map(item=>{
            if(item.key===key){
                item.goodsDesc = e.target.value
            }
        })
        this.setState({
            data:newData
        })
    }
    columns = [
        {
            dataIndex: 'key',
            align:'center',
        },
        {
            align:'center',
            render:text=><span><PlusOutlined onClick={()=>this.addRow()} className='myAddIcon'/>
                            <MinusOutlined onClick={()=>this.removeRow(text)} style={{marginLeft:'5px',cursor:'pointer',display:this.state.data.length===1?'none':'inline-block'}} className='myAddIcon'/></span>
        },
        {
            title:'商品编码',
            dataIndex: 'goodsId',
            align:'center',
            render:text=> <Input style={{textAlign:'center',width:'323px'}} value={text}/>
        },
        {
            title:'商品名称',
            dataIndex: 'goodsName',
            align:'center',
            render:(text,record)=><Dropdown overlay={(<Menu>
                {this.state.goodsData.map((item,index)=>{
                    return <Menu.Item onClick={()=>this.goodsSelected(item)} key={index}>{item.goodsName}</Menu.Item>
                })}
            </Menu>)}>
                <Button className='addToDepotBtn'>
                    {text}<DownOutlined />
                </Button>
            </Dropdown>
        },
        {
            title:'商品规格',
            dataIndex: 'goodsType',
            align:'center',
            render:text=> <Input style={{textAlign:'center'}} value={text}/>
        },
        {
            title:'单位',
            dataIndex: 'goodsUnit',
            align:'center',
            render:text=> <Input style={{textAlign:'center'}} value={text}/>
        },
        {
            title:'采购数',
            dataIndex: 'stockInOut',
            align:'center',
            render:(text,record) => <Input style={{textAlign:'center'}}  onChange={e=>this.changeNum(e,record.key)}/>
        },
        {
            title:'采购单价',
            dataIndex: 'purchaseCost',
            align:'center',
            render:(text,record) => <Input style={{textAlign:'center'}}  onChange={e=>this.changePrice(e,record.key)}/>
        },
        {
            title:'小计',
            dataIndex: 'price',
            align:'center',
            render:(text,record) => <Input style={{textAlign:'center'}}  value={text!=='NaN'?text:''}  onChange={e=>this.changeNote(e,record.key)}/>
        },
    ]

    depotSelected=(name)=>{
        this.setState({
            depotSelectValue:name
        })
    }
    changeCreator(e){
        this.setState({
            creator:e.target.value
        })
    }
    myNote(e){
        this.setState({
            note:e.target.value
        })
    }
    subInOrder(){
        let creator = this.state.userName
        let date = this.state.myDate
        let userName = this.state.creator
        let id = this.state.myOrderId
        let note = this.state.note
        let type = this.state.myType
        let userId = this.state.userId

        let depotData = this.state.myDepot
        let depot = this.state.depotSelectValue
        let depotId = 0
        depotData.map(item=>{
            if(item.repositoryName===depot){
                depotId = item.key
            }
        })

        let data = {
            creator:creator,
            handleBy:userName,
            list:[],
            date:date,
            receiptOutNo:id,
            receiptOutRemarks:note,
            repositoryId:depotId,
            stockInOutType:type,
            userId:userId
        }

        let goodsData = this.state.data
        goodsData.map(item=>{
            delete item.goodsName
            delete item.goodsDesc
            delete item.goodsType
            delete item.goodsUnit
            delete item.key
            return item
        })
        data.list = [...goodsData]
        axios({
            url:'/api/goods/addWarehousingRecord',
            method:'post',
            data:data
        }).then(res=>{
            // if(res.data.code===200){
                message.success('新增成功')
                this.props.history.push('/homepage/purchaseorders')
            // }
        })
    }
    render() {
        return (
            <div>
                <Row>
                    <Col id='lCol'>
                        <span>*</span>
                        <span>供应商</span>
                        <Dropdown overlay={this.menu}>
                            <Button>
                                {this.state.depotSelectValue}<DownOutlined />
                            </Button>
                        </Dropdown>
                    </Col>
                    <Col id='rCol'>
                        <span>采购日期</span>
                        <DatePicker
                            showTime
                            onChange={this.onChange}
                            onOk={this.onOk.bind(this)}
                            value={Moment(today,dateFormat)}
                        />
                    </Col>
                </Row>
                <Row id='tableRow'>
                    <Col style={{width:'100%'}}>
                        <Table id='addToDepotTable' bordered={true} pagination={pageNation} columns={this.columns} dataSource={this.state.data}/>
                    </Col>
                </Row>
                <Row id='detailsRow'>
                    <Col id='myLeftCol' span={6}>
                        <div>
                            <span><span>*</span>其他金额</span>
                            <Input onChange={this.changeMoney} className='inputAndBtn'/>
                        </div>
                        <div>
                            <span><span>*</span>采购订单号</span>
                            <Input value={this.state.myOrderId} style={{width:'350px'}} type="text"/>
                        </div>
                        <div>
                            <span>经办人</span>
                            <Input value={this.state.creator} onChange={e=>this.changeCreator(e)} className='inputAndBtn'/>
                        </div>
                    </Col>
                    <Col id='myRightCol' span={6}>
                        <div>
                            <span>备注</span>
                            <TextArea value={this.state.note} onChange={e=>this.myNote(e)} style={{width:'350px',marginLeft:'10px'}} rows={3} />
                        </div>
                        <div>
                            <span>制单人</span>
                            <Input placeholder={this.state.userName} disabled style={{width:'350px',marginLeft:'10px'}}/>
                        </div>
                    </Col>
                </Row>
                <Row id='bottomRow'>
                    <Col>
                        <Button>取消</Button>
                        <Button onClick={this.subInOrder.bind(this)}>保存</Button>
                    </Col>
                </Row>
            </div>
        );
    }
    componentDidMount() {
        axios({
            url: '/api/repository/queryRepositoryByPage',
            method: 'post',
            data: {currentPage: 1, perSize: 999}
        }).then(res => {
            let data = res.data.data.repositoryList.filter((item) => {
                item.key = item.repositoryId
                delete item.repositoryId
                return item
            })
            let allType = {key: 1, repositoryName: '全部仓库'}
            data.unshift(allType)
            this.setState({
                myDepot: data
            })
        })
        axios({
            url:'/api/goods/selectCurrentPageGoods',
            method:'post',
            data:{currentPage:1,perSize:7}
        }).then(res=>{
            let num=1
            let a = 0
            let data = res.data.data.filter((item)=>{
                item.key = num
                num++
                return item
            })
            this.setState({
                goodsData:data
            })
        })


        let now = new Date();
        let year = now.getFullYear(); //得到年份
        let month = now.getMonth();//得到月份
        let date = now.getDate();//得到日期
        let hour = now.getHours();//得到小时
        let minu = now.getMinutes();//得到分钟
        let sec = now.getSeconds();//得到秒
        this.setState({
            myOrderId:year+''+month+''+date+''+hour+''+minu+''+sec
        })

        let userName = JSON.parse(sessionStorage.getItem("username"))
        this.setState({
            userName:userName
        })

        let userId = JSON.parse(sessionStorage.getItem("userdata")).userId
        this.setState({
            userId:userId
        })
    }
}

export default withRouter(AddPurchaseOrder);